package com.servlet;

import com.dao.UserDAO;
import com.dao.impl.UserDAOImpl;
import com.entity.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/*
 *
 *@author XCH
 *@date2024 - 11 - 26
 *
 */
@WebServlet("/reg")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        UserDAO userDAO = new UserDAOImpl();
        PrintWriter out = resp.getWriter();

        // 检查用户名是否已存在
        User existingUser = userDAO.getUserByUsername(username);

        if (existingUser != null) {
            // 如果用户名已存在，返回错误信息
            resp.setContentType("application/json");
            out.print("{\"success\":false, \"message\":\"用户名已存在\"}");
        } else {
            // 创建新用户并插入数据库
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setEmail(email);
            newUser.setPhone(phone);

            boolean success = userDAO.insertUser(newUser);

            if (success) {
                resp.setContentType("application/json");
                out.print("{\"success\":true, \"message\":\"注册成功\"}");
            } else {
                resp.setContentType("application/json");
                out.print("{\"success\":false, \"message\":\"注册失败，请稍后重试\"}");
            }
        }

        out.flush();
        out.close();
    }
}
